from django.contrib import admin


from jobs.models import Daemon, Job

from django.db.models import Q

from jobs import Execute
  
def Daemon_stop(modeladmin, request, queryset):
  for object in queryset: 
    Execute(object.command, 'stop', id=object.id).wait()

Daemon_stop.short_description = "Stop selected daemons"

def Daemon_start(modeladmin, request, queryset):
  for object in queryset:
    Execute(object.command, 'start', id=object.id).wait()
Daemon_start.short_description = "Start selected daemons"

def Daemon_restart(modeladmin, request, queryset):
  for object in queryset:
    Execute(object.command, 'restart', id=object.id).wait()
Daemon_restart.short_description = "Restart selected daemons"

class DaemonAdmin(admin.ModelAdmin):
    actions = [Daemon_stop, Daemon_start, Daemon_restart]
    list_display = ('command', 'pid', 'status', 'info',)
    list_filter = ('command', )
    search_fields = ('pid',)
    
admin.site.register(Daemon, DaemonAdmin)

def Job_reschedule(modeladmin, request, queryset):
  for object in queryset.filter(Q(status='successful') | Q(status='unsuccessful')):
    object.schedule()
    object.save()
Job_reschedule.short_description = "Reschedule selected jobs"

def Job_rescheduleFORCE(modeladmin, request, queryset):
  for object in queryset.all():
    object.schedule()
    object.save()
Job_rescheduleFORCE.short_description = "Force reschedule of selected jobs(DANGEROUS)"

class JobAdmin(admin.ModelAdmin):
    actions = [Job_reschedule, Job_rescheduleFORCE]
    list_display = ('id', 'status', 'content_type', 'method', 'object_id', 'start_date', 'duration',)
    list_filter = ('method', 'status')
    search_fields = ('object_id',)
    
admin.site.register(Job, JobAdmin)

